package hpp.tencentTest;

/**
 * 在一组数的编码中，若任意两个相邻的代码只有一位二进制数不同， 则称这种编码为格雷码(Gray Code)，请编写一个函数，使用递归的方法生成N位的格雷码。
 * 给定一个整数n，请返回n位的格雷码，顺序为从0开始。
 * 测试样例：
 * 1
 * 返回：["0","1"]
 * Created by hpp on 2017/9/11.
 */
public class GrayCode {


    public static void main(String[] args) {
//        System.out.println(getGray(2));
        for (String item : getGray(3)) {
            System.out.print(item + " ");
        }
        System.out.println();
        for (String item : getGray1(3)) {
            System.out.print(item + " ");
        }
    }

    public static String[] getGray(int n) {
        // write code here
        int m = 1 << n;
        String[] r = new String[m];
        if (n == 1) {
            r[0] = "0";
            r[1] = "1";
            return r;
        }
        String[] temp = getGray(n - 1);
        int j = 0;
        for (int i = 0; i < m; i++) {
            if (i < m / 2) {
                r[i] = "0" + temp[j++];
            } else {
                r[i] = "1" + temp[--j];
            }
        }
        return r;
    }


    public static String[] getGray1(int n) {

        int m = 1 << n;
        String[] arr = new String[m];
        for (int i = 0; i < m; i++) {
            int grayNum = i ^ (i / 2);
            String binaryGray = Integer.toBinaryString(grayNum);
            int length = binaryGray.length();
            if (length < n) {
                StringBuilder str = new StringBuilder("");
                for (int j = 0; j < n - length; j++) {
                    str.append("0");
                }
                binaryGray = str.append(binaryGray).toString();
            }
            arr[i] = binaryGray;
        }
        return arr;

    }

}
